package ec.atreasure.com.core.download;

import android.os.AsyncTask;

import java.util.WeakHashMap;

import ec.atreasure.com.core.net.RestCreator;
import ec.atreasure.com.core.net.callback.IError;
import ec.atreasure.com.core.net.callback.IFailure;
import ec.atreasure.com.core.net.callback.IRequest;
import ec.atreasure.com.core.net.callback.ISuccess;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Description :文件下载控制器
 * Created by wangjin on 2019/6/24.
 * Job number：
 * Phone ：18301070822
 * Email： 120182051@qq.com
 * Person in charge : 汪渝栋
 * Leader：
 */
public final class DownloadHandler {
    //请求参数
    private final WeakHashMap<String, Object> mParams;

    //请求地址
    private final String url;

    //请求开始/结束回调
    private final IRequest requestCallback;

    //请求错误回调
    private final IError errorCallback;

    //请求失败回调
    private final IFailure failureCallback;

    //请求成功回调
    private final ISuccess successCallback;

    //下载文件目录
    private final String downloadDir;

    //下载文件扩展名
    private final String extension;

    //下载文件名
    private final String downloadFileName;

    public DownloadHandler(WeakHashMap<String, Object> mParams,
                           String url, IRequest requestCallback,
                           IError errorCallback, IFailure failureCallback,
                           ISuccess successCallback, String downloadDir,
                           String extension, String downloadFileName) {
        this.mParams = mParams;
        this.url = url;
        this.requestCallback = requestCallback;
        this.errorCallback = errorCallback;
        this.failureCallback = failureCallback;
        this.successCallback = successCallback;
        this.downloadDir = downloadDir;
        this.extension = extension;
        this.downloadFileName = downloadFileName;
    }

    /**
     * 开始下载，对服务器进行访问并处理下载正常及异常状态逻辑调用
     */
    public final void startDownload() {
        if (requestCallback != null) {
            requestCallback.onStartRequest();
        }

        RestCreator.getRestService()
                .download(url, mParams)
                .enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                        if (response.isSuccessful()) {
                            final ResponseBody responseBody = response.body();
                            final SaveFileTask saveFileTask = new SaveFileTask(requestCallback, successCallback);
                            saveFileTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR
                                    , downloadDir, extension, responseBody, downloadFileName);

                            //判断任务是否完成，避免出现文件下载不全
                            if (saveFileTask.isCancelled()) {
                                if (requestCallback != null) {
                                    requestCallback.onEndRequest();
                                }
                            }
                        } else {
                            if (errorCallback != null) {
                                errorCallback.onError(response.code(), response.message());
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable t) {
                        if (failureCallback != null) {
                            failureCallback.onFaild();
                        }
                    }
                });
    }
}
